﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link href="../lib/css/layui.css" rel="stylesheet" type="text/css" />
    <script src="../lib/layui.js"></script>
    
    <script>
        function isEmptyObject(obj) {
            for (var key in obj) {
                return false;
            }
            return true; 
        }
    </script>
</head>
<body>


    <blockquote class="layui-elem-quote"> 判断一个对象是否为空</blockquote>

    <div class="layui-row">
        <div class="layui-btn" id="btn1">判断1</div>
        <div class="layui-btn" id="btn2">判断2</div>
        <div class="layui-btn" id="btn3">判断3</div>
        <div class="layui-btn" id="btn4">判断4</div>
        <pre class="layui-code" lay-title="html代码">

        </pre>

    </div>
    
<div class="layui-row">结果</div>
<div id="result">

</div>




<script>

    var tmpJson1;
    var tmpJson2 = {};
    var tmpJson3 = { "UserName": "张三" };
    var tmpJson4 = [{ 'UserName': '张三','Sex':'男' }, { 'UserName': '李四','Sex':'女' }];


    var $ = layui.$;

    $(function() {
        $("#btn1").click(function() {
            if (isEmptyObject(tmpJson1)) {
                $("#result").html("var tmpJson1; 直接定义是空对象");
            }
        });

        $("#btn2").click(function () {
            if (isEmptyObject(tmpJson2)) {
                $("#result").html("var tmpJson2={}; 是空对象");
            }
        });

        $("#btn3").click(function () {
            if (isEmptyObject(tmpJson3)) {
                $("#result").html("var tmpJson3 = {\"UserName\":\"张三\"}; 是空对象");
            } else {
                $("#result").html("var tmpJson3 = {\"UserName\":\"张三\"}; 不是空对象");
            }
        });

        $("#btn4").click(function () {
            if (isEmptyObject(tmpJson4)) {
                $("#result").html("    var tmpJson4 = [{ 'UserName': '张三' }, { 'UserName': '李四' }];                是空对象");
            } else {
                for (var key in tmpJson4) {
                    console.log(key);
                }

                $.each(tmpJson4, function(index, elem) {
                    console.log("当前的Key" + index + ",姓名:"+elem.UserName + ",性别:" + elem.Sex);
                });

                $("#result").html("    var tmpJson4 = [{ 'UserName': '张三' }, { 'UserName': '李四' }];                不是空对象");

            }
        });
    });

    layui.code({ encode: true });

  

</script>
</body>
</html>